import Term from '../../models/terms'
let response={
  code:10001,
  message:'',
  data:{}
}
export async function createTerm(ctx) {
  const term = new Term(ctx.request.body.term);
  try {
    await term.save();
  } catch (err) {
    ctx.throw(422, err.message);
  }

// 此处可以调用存储过程中的自定义方法
  const str = term.method1();

  ctx.body = Object.assign(response,{data:term,message:'成功创建一期答题'});
}


export async function getTerms(ctx) {
  const terms = await Term.find().sort('terms_create_time').exec();
  ctx.body = Object.assign(response,{data:terms,message:'成功获取所有答题'});
}

export async function getTerm(ctx, next) {
  try {
    const term = await Term.findById(ctx.params.id)
    if (!term) {
      ctx.throw(404)
    }

    ctx.body = Object.assign(response,{data:term,message:'成功获取一期答题'});
    if (next) {
      return next()
    }
  } catch (err) {
     ctx.body = Object.assign(response,{data:[],message:'未查询到相关数据',code:10004});
  }


}


export async function updateTerm(ctx) {

  const term = ctx.body.data
 Object.assign(term, ctx.request.body.term)

  await term.save().then(term => {
      ctx.body = Object.assign(response,{data:term,message:'修改期数数据成功'});
  }).catch(err => {

     ctx.body = Object.assign(response,{data:[],message:'数据库错误更新失败',code:10004});
  })

}


export async function deleteTerm(ctx) {
  const term = ctx.body.data
 Object.assign(term, ctx.request.body.term)
  await term.remove().then(term => {
    ctx.body = Object.assign(response,{data:term,message:'成功删除一期答题'});
  }).catch(err => {
     ctx.body = Object.assign(response,{data:term,message:'删除答题失败',code:10004});
  })
}
